package org.study.hadoop.md.ch4;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 分层结构1：给定一个帖子和评论的列表，创建一个结构和的XML层次结构，嵌套地标识帖子及其相关评论
 */
public class PostCommentBuildingDriver extends Configured implements Tool {

    public static class PostCommentHierarchyReducer extends Reducer<Text, Text, Text, NullWritable> {
        private ArrayList<String> comments = new ArrayList<String>();
        private String post = null;

        private String nestElements(String post, List<String> comments) {
            StringBuilder sb = new StringBuilder("P" + post);
            for (String comment : comments) {
                sb.append("\n\t" + "C" + comment);
            }
            return sb.toString();
        }

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            post = null;
            comments.clear();
            for (Text text : values) {
                if (text.charAt(0) == 'P') {
                    post = text.toString().substring(1, text.toString().length()).trim();
                } else {
                    comments.add(text.toString().substring(1, text.toString().length()).trim());
                }
            }
            if (post != null) {
                String postWithCommentChildren = nestElements(post, comments);
                context.write(new Text(postWithCommentChildren), NullWritable.get());
            }
        }
    }

    public static class CommentMapper extends Mapper<Object, Text, Text, Text> {
        private Text outKey = new Text();
        private Text outValue = new Text();

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
            String postId = parsed.get("PostId");
            if (postId == null) {
                return;
            }
            outKey.set(postId);
            outValue.set("C" + value.toString());
            context.write(outKey, outValue);
        }
    }

    public static class PostMapper extends Mapper<Object, Text, Text, Text> {
        private Text outKey = new Text();
        private Text outValue = new Text();

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
            String postId = parsed.get("Id");
            if (postId == null) {
                return;
            }
            outKey.set(postId);
            outValue.set("P" + value.toString());
            context.write(outKey, outValue);
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path outPath = new Path("out");
        Path inPath1 = new Path("post.txt");
        Path inPath2 = new Path("comment.txt");
        FileSystem fs = outPath.getFileSystem(getConf());
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }
        Job job = Job.getInstance(getConf(), "PostCommentHierarchy");
        job.setJarByClass(PostCommentBuildingDriver.class);
        MultipleInputs.addInputPath(job, inPath1, TextInputFormat.class, PostMapper.class);
        MultipleInputs.addInputPath(job, inPath2, TextInputFormat.class, CommentMapper.class);
        job.setReducerClass(PostCommentHierarchyReducer.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        FileOutputFormat.setOutputPath(job, outPath);
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new PostCommentBuildingDriver(), args);
        System.exit(res);
    }
}
